package com.itheima;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import javax.xml.parsers.SAXParser;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
    服务端实现的需求：
        1.创建服务端，绑定端口
        2.接收客户端的socket连接，交给一个独立的线程来处理
        3.把当前连接的客户端socket存入到一在线socket集合中保存
        4.接收客户端的消息，然后推送给当前所有在线的socket接收
 */
public class ChatServer {
    // 定义一个静态集合，保存登陆用户的Socket和对应的用户信息
    public static Map<Socket, User> allSocketOnLine = new HashMap<>();

    // 定义一个静态集合，保存已注册用户User对象
    public static List<User> registerUsers = new ArrayList<>();

    static {
        //创建解析器
        SAXReader reader = new SAXReader();


        try {
            //通过解析器获得文档对象
            Document document = reader.read("chatserver\\src\\admins.xml");
            Element root = document.getRootElement();
            List<Element> users = root.elements();
            for (Element user : users) {
                boolean isAdmin =Boolean.parseBoolean(user.attributeValue("isAdmin"));
                String userName = user.element("userName").getText();
                String sex = user.element("sex").getText();
                String ip = user.element("ip").getText();
                int age =Integer.parseInt(user.element("age").getText()) ;
                registerUsers.add(new User(userName,sex,ip,age,isAdmin));
            }

            //创建对象流读取data.txt中的user对象
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("chatserver\\userData\\Data.txt"));
            User user;
            while ((user=(User) ois.readObject())!=null){
                registerUsers.add(user);
            }


        } catch (DocumentException | FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {




        // 为了方便测试，预先注册2个普通用户
        registerUsers.add(new User("zhangsan", "男","127.0.0.1", 18, false));
        registerUsers.add(new User("lisi", "女","127.0.0.1", 22, false));

        System.out.println("预加载测试用户：");



        for (User user : registerUsers) {
            System.out.println(user);
        }

        try {
            ServerSocket ss = new ServerSocket(9999); //注意：如果启动后有端口冲突，可以自己重新设定
            System.out.println("服务端已启动!");
            while (true) {
                Socket socket = ss.accept();
                // 为当前登录成功的socket分配一个独立的线程来处理与之通信
                new ChatServerThread(socket).start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
